/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "utils.h"
#include "device/csr.h"
#include <mc/exception.h>

namespace devmon {

std::optional<unit> utils::get_connector_unit(const mc::dict& connector) {
    // 检查 Unit 字段是否存在
    if (!connector.contains("Unit")) {
        elog("connector missing Unit field");
        return std::nullopt;
    }

    const auto& unit_variant = connector["Unit"];
    if (!unit_variant.is_dict()) {
        elog("Unit field is not a dictionary, got type: ${type}",
             ("type", unit_variant.get_type_name()));
        return std::nullopt;
    }

    unit unit_info;
    try {
        mc::from_variant(unit_variant, unit_info);

        // 验证 unit_info 的必要字段
        if (unit_info.m_type.empty()) {
            elog("unit type is empty");
            return std::nullopt;
        }

        return unit_info;

    } catch (const mc::bad_cast_exception& e) {
        elog("failed to convert Unit field to unit struct, error: ${error}", ("error", e.what()));
        return std::nullopt;
    } catch (const std::exception& e) {
        elog("unexpected error when parsing Unit field, error: ${error}", ("error", e.what()));
        return std::nullopt;
    }
}

BuildType utils::get_build_type() {
#if defined(BUILD_TYPE)
#if BUILD_TYPE == BUILD_TYPE_DEBUG
    return BuildType::Debug;
#elif BUILD_TYPE == BUILD_TYPE_RELEASE
    return BuildType::Release;
#elif BUILD_TYPE == BUILD_TYPE_DT
    return BuildType::Dt;
#else
    return BuildType::Unknown;
#endif
#else
    return BuildType::Unknown;
#endif
}

} // namespace devmon